package com.learn.fourday;

import java.util.ArrayList;

/**
 * @author ln
 * @Description: ${todo}
 * @date 2020/12/10
 */
public class VarialableTest {
    static final int THREAD_NUMBER=2;//线程数
    static final int LOOP_NUMBER=200;//循环次数

    public static void main(String[] args) {
        ThreadUnsafe test = new ThreadUnsafe();
        for (int i=0;i<THREAD_NUMBER;i++){
            new Thread(()->{
                test.method1(LOOP_NUMBER);
            },"THread"+(i+1)).start();
        }

    }
}

class ThreadUnsafe{
    // method2(),method3()访问的是共享资源list，所以会由线程安全问题
    ArrayList<String> list=new ArrayList();

    public void method1(int loopNumber){
        for (int i=0;i<loopNumber;i++){
            method2();
            method3();
        }
    }

    private void method2() {
        list.add("1");
    }

    private void method3() {
        list.remove(0);
    }
}


class Threadsafe{

    public void method1(int loopNumber){
        ArrayList<String> list=new ArrayList();
        for (int i=0;i<loopNumber;i++){
            method2(list);
            method3(list);
        }
    }

    private void method2(ArrayList<String> list) {
        list.add("1");
    }

    private void method3(ArrayList<String> list) {
        list.remove(0);
    }
}
